<?php
session_start();
include 'dbconfig.php'; 

mysql_select_db($db, $con);

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);


// Try connecting to RC
function RZauth($username, $password) {
	// HACK
	
	return true;

	
	@$mbox = imap_open("{pop3.Uni-Osnabrueck.de/pop3:110}INBOX",$username,$password);

	if ($mbox === false)
		$out = false;
	else {
		$out = true;
		@imap_close($mbox);
	}
	return $out;
}

function userExists($username) {
	$username = md5($username);
	$query = "SELECT * FROM users WHERE username = '$username' LIMIT 1";
	$result =  mysql_query($query);
	return (1 == mysql_num_rows($result));
}

function localAuth($username, $password) {
	$username = md5($username);
	$password = md5($password);
	$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 1";
	$result =  mysql_query($query);
	return (1 == mysql_num_rows($result));	
}

function newUser($username, $password) {
	$username = md5($username);
	$password = md5($password);
	$query = "INSERT INTO users VALUES (0, '$username', '$password')";
	mysql_query($query);
}

if (userExists($username)) {
	// User is there, try to log in
	if (localAuth($username, $password)) {
		// All OK, log in
		$_SESSION['uid'] = md5($username);
		echo "ok";
	} else {
		// Wrong password
		echo "password";
	}
} else {
	// Either wrong username or new user.
	if (RZauth($username, $password)) {
		newUser($username, $password);
		$_SESSION['uid'] = md5($username);
		echo "new";
	} else {
		echo "username";
	}
}

?>
